import 'package:dio/dio.dart';
// import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:wishdom_mall/pages/home/components/home_banner.dart';
import 'package:wishdom_mall/pages/home/components/home_goods.dart';
import 'package:wishdom_mall/pages/home/components/home_nav.dart';
import 'package:wishdom_mall/pages/home/components/home_search.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 定义状态变量
  Map resData = {};
  List bannerList = [];
  List navList = [];
  List adList = [];
  List goodsList = [];

  @override
  void initState() {
    getResData();
    super.initState();
  }

  void getResData() async {
    Dio dio = Dio();
    Response res = await dio
        .get('http://smart-shop.itheima.net/index.php?s=/api/page/detail');
    // 更新状态
    setState(() {
      resData = res.data['data']['pageData'];
      bannerList = resData['items'][1]['data'];
      navList = resData['items'][3]['data'];
      adList = resData['items'][4]['data'];
      goodsList = resData['items'][6]['data'];
    });
    // if (kDebugMode) {
    //   print(bannerList);
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            '智慧商城',
            style: TextStyle(color: Colors.white),
          ),
          backgroundColor: Colors.red,
          centerTitle: true,
        ),
        body: ListView(
          // 处理listview嵌套报错
          shrinkWrap: true,
          children: [
            const HomeSearch(),
            HomeBanner(bannerList: bannerList),
            HomeNav(navList: navList),
            // 首页广告位
            adList.isNotEmpty
                ? GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/search');
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(top: 8, bottom: 8),
                      child: Image.network('${adList[0]['imgUrl']}'),
                    ),
                  )
                : Container(),
            // 猜你喜欢
            const Padding(
              padding: EdgeInsets.only(top: 4, bottom: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Text('--猜你喜欢--')],
              ),
            ),
            // 商品列表
            HomeGoods(goodsList: goodsList)
          ],
        ));
  }
}
